//
//  GetMoneyController.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/9/7.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD

class GetMoneyController: BaseViewController {
    
    var model : BankCardInfoModel?
    
    var lastModel : MyGoldBeanModel?

    
    var block : (() -> ())?
    
    
    lazy var bottomView : OrderBottomView = {
        
        let temp : OrderBottomView = Bundle.main.loadNibNamed(self.StringFromClass(classType: OrderBottomView.self), owner: nil, options: nil)?.first as! OrderBottomView
        
        temp.frame = CGRect(x: 0, y: 0, width: KScreenW, height: 90)
        
        temp.btn.setTitle("确认提现", for: .normal)
        
        temp.isHidden = true
        
        temp.delegate = self
        
        return temp
        
    }()


    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "提现"
        
    
        
        groupTableView.tableFooterView = bottomView
        
        bottomView.backgroundColor = UIColor.viewBgGrey()
        
        bottomView.isHidden = model == nil ? true : false
        
        groupTableView.backgroundColor = UIColor.viewBgGrey()
        
        
        groupTableView.register(UINib(nibName: StringFromClass(classType: GetMoneyTopNoCarCell.self), bundle: nil), forCellReuseIdentifier: GetMoneyTopNoCarCell.identifer())
        
        groupTableView.register(UINib(nibName: StringFromClass(classType: GetMoneyTopHaveCarCell.self), bundle: nil), forCellReuseIdentifier: GetMoneyTopHaveCarCell.identifer())

        groupTableView.register(UINib(nibName: StringFromClass(classType: GetMoneyFieldCell.self), bundle: nil), forCellReuseIdentifier: GetMoneyFieldCell.identifer())

        

    }
    
    
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if model == nil {
            return
        }
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=member_index&a=member_state", parameters: nil) { [weak self] (responseObject, error) in
            
            if error == nil{
                
                
                if self?.model != nil{
                    
                    let temp = responseObject?["datas"]?["paypwd_state"]
                    
                    
                    if temp != nil{
                        
                        
                        self?.model?.paypwd_state = temp as! String
                        
                        
                    }
                    
                    
                    
                }
                
            }
            
            
        }
        
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        SVProgressHUD.dismiss()
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

   
}


extension GetMoneyController : OrderBottomViewDeleage{
    
    func orderBottomViewBtnDidTap(){
        
        if model?.paypwd_state == "0" {
            
            setupPassword()
            
        } else {
            
            verifyPassword(bool: { (temp) in
                
                if temp == true{
                    
                    self.makeSurePay()
                    
                    
                }else{
                    
                    QL1("密码错误")
                    
                }
            })
            
        }

    
    }
    
    
    
    
    
    
    
    func setupPassword() {
        
        let tempVC = UIAlertController(title: nil, message: "您还未设置支付密码", preferredStyle: .alert)
        
        let action1 = UIAlertAction(title: "去设置", style: .default) { (action) in
            
            let temp = UpLoadIconController()
            
            temp.urlStr = self.model!.set_paypwd_url
            
            self.navigationController?.pushViewController(temp, animated: true)
            
        }
        
        
        
        let action2 = UIAlertAction(title: "取消", style: .default) { (action) in
            
            
        }
        
        tempVC.addAction(action2)
        tempVC.addAction(action1)
        
        present(tempVC, animated: true, completion: nil)
        
        
        
    }
    
    
    
    
    
    func verifyPassword(bool : @escaping (_ password : Bool) -> ()) {
        
        
        let tempVC = UIAlertController(title: nil, message: "请输入支付密码", preferredStyle: .alert)
        
        let action1 = UIAlertAction(title: "取消", style: .default) { (action) in
            
        }
        
        
        
        let action2 = UIAlertAction(title: "确定", style: .default) { (action) in
            
            let passwordTextField = tempVC.textFields?.first
            
            var parmeter  = [String : AnyObject]()
            
            parmeter["password"] = passwordTextField?.text as AnyObject
            
            NetworkTools.shared.sendRequest(method: .POST_METHOD, pathStr: "mobile/index.php?c=member_buy&a=check_password", parameters: parmeter, completionHandler: {(responseObject, error) in
                
                if error == nil{
                    
                    
                    bool(true)
                    
                    
                }else{
                    
                    SVProgressHUD.showError(withStatus: error?.domain)
                    
                    
                }
                
            })
            
            
        }
        
        
        tempVC.addTextField { (textField) in
            textField.keyboardType = .numberPad
            textField.isSecureTextEntry = true
            
            // 根据原有字符串生成属性字符串
            let placeholderStr = "请输入六位数字密码"
            
            let strM = NSMutableAttributedString(string:placeholderStr )
            
            strM.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 15), range:NSMakeRange(0, placeholderStr.characters.count))
            
            strM.addAttribute(NSForegroundColorAttributeName, value: UIColor.colorWith(r: 199, g: 199, b: 205), range:NSMakeRange(0, placeholderStr.characters.count) )
            
            textField.attributedPlaceholder = strM
            
            
            
        }
        
        tempVC.addAction(action1)
        tempVC.addAction(action2)
        
        present(tempVC, animated: true, completion: nil)
        
        
    }
    
    
    
    
    
    func makeSurePay() {
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["pdc_amount"] = model?.willPayMoney as AnyObject
        
        parmeter["card_id"] = model?.card_id as AnyObject

        NetworkTools.shared.sendRequest(method: .POST_METHOD, pathStr: "mobile/index.php?c=member_fund&a=pd_cash_add", parameters: parmeter) { [weak self] (responseObject, error) in
            
            
            
            if error == nil {
                
                if self?.block != nil{
                
                    self?.block!()

                }
                
                
                self?.navigationController?.popViewController(animated: true)
                
            }else{
                
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
            
        }
        
    }


}





extension GetMoneyController{
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        if model == nil {
            return 1

        } else {
            return 2

        }
        
        
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 1
  
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var tableCell : UITableViewCell? = nil
        
        if indexPath.section == 0 {
            
            if model == nil {
                let tempCell : GetMoneyTopNoCarCell =  tableView.dequeueReusableCell(withIdentifier: GetMoneyTopNoCarCell.identifer()) as! GetMoneyTopNoCarCell
                
                tableCell = tempCell
            } else {
                
                let tempCell : GetMoneyTopHaveCarCell =  tableView.dequeueReusableCell(withIdentifier: GetMoneyTopHaveCarCell.identifer()) as! GetMoneyTopHaveCarCell
                
                tempCell.model = model
                
                tableCell = tempCell
            }
            

            
            
        }else{
            
            
            let tempCell : GetMoneyFieldCell =  tableView.dequeueReusableCell(withIdentifier: GetMoneyFieldCell.identifer()) as! GetMoneyFieldCell
            
            tempCell.model = model

            tableCell = tempCell
            
            
            
        }
        
        
        
        return tableCell!
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            
            if model == nil {
                
                return 55
                
            } else {
                
                return  90

            }
        }else{
            
            return 136
        }
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 0 {
            
            return 0.00001

        } else {
            
            return 20

        }
        
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        return 0.00001
    }
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.section == 0 {
            
            if model == nil {
                
                let temp = AddBankCardVC()
                
                temp.block = {() -> () in
                    
                    self.lastModel?.datas?.predeposit_info?.have_card = "1"
                
                    self.loadBankCardData()
                
                }
                
                
                navigationController?.pushViewController(temp, animated: true)
            } else {
                let temp = MyBankCarListVC()
                temp.lastV = self
                navigationController?.pushViewController(temp, animated: true)

            }
            
        }         
        
    }
    
    
    
    
    
    
    
    
    
    func loadBankCardData() {
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=member_bank_card&a=card_list", parameters: nil) { [weak self] (responseObject, error)  in
            
            
            if error == nil {
                
       
                
                let temp = responseObject!["datas"]!["card_list"] as? [[String : AnyObject]]
                
          
                if temp != nil{
                    
                    if temp!.count > 0{
                        
                        self?.model = BankCardInfoModel(dic: temp![0])
                        
                        self!.groupTableView.reloadData()
                    
                    }
                
                

                }
                
                
                
            }else{
                
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
        }
    }
    
    
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        view.endEditing(true)
    }
    
    
    
    
    
    
    
}


